/*-------------------------------------*/
// VALIDATION FORM 	1.2 /
//                                    	/
// Creato Marco Pastorello 2008      	/
//                                    	/
// marco.pastorello@as3.it									  	/
//                                    	/
// Last revision: 06/04/09              /
/*-------------------------------------*/

/* parte da aggiungere alla pagina nel BODY:
 <!-- VALIDATION FORM START -->
 <script type="text/javascript" src="../../js/prototype.js"></script>
 <script type="text/javascript" src="../../js/error_messages_ita.js"></script>
 <script type="text/javascript" src="../../js/validation_form.js"></script>
 <!-- VALIDATION FORM END -->
 */
var flgErrPag;
var elementiMancanti = new Array();


function isNull(target){
	if (target==null || target.toString()==""){
		return true;
		}else return false;
	}



String.prototype.entityify = function () {
    return this.replace(/&/g,"&amp;")
	.replace(/</g,"&lt;")
	.replace(/>/g, "&gt;")
	.replace(/à/g, "&agrave;")
	.replace(/è/g, "&egrave;")
	.replace(/ì/g, "&igrave;")
	.replace(/ò/g, "&ograve;")
	.replace(/ù/g, "&ugrave;")
	.replace(/é/g, "&eacute;")
	.replace(/€/g, "&euro;");

	
	
};








function obbligatori(target){
    if (target == '') {
        target = 0;
    }
    var field;
    var elements = $(target).getElements();
    var result = false;
    m = 0;
	elementiMancanti = new Array();
    for (i = 0; i < elements.length; i++) {
        field = $(elements[i]);
        var classes = field.classNames().inspect()
        
        if (field.value == "" && classes.include('req')) {
            //				eval("document.forms['"+target+"']."+aCampi[i]+".select()");	
            if (!isNull(field.getAttribute('alt'))) {
                elementiMancanti[m] = field.getAttribute('alt');
            }
            else if (!isNull(field.getAttribute('title'))) {
                    elementiMancanti[m] = field.getAttribute('title');
                }
                else if (!isNull(field.name)) {
                    elementiMancanti[m] = field.name;
                }
            
            
            m++;
        }
    }
    if (m == 0) 
        result = true;
    return result;
    
}
function pulisciStringa(separatore,str){
var result=str.gsub(separatore, ' ');
return result.entityify();
}

function correggiForm(target){
var separatore="##";

    var myForm = $(target.id);
    //Disable Privacy field
	
	if($(myForm['legge_privacy'])){
    Form.Element.disable($(myForm['legge_privacy']));
	}
	
    var myInputName = $(document.createElement('input'))
    var myInputAlt = $(document.createElement('input'))
    var myInputValue = $(document.createElement('input'))
    myInputName.setAttribute('type', 'hidden');
    myInputAlt.setAttribute('type', 'hidden');
    myInputValue.setAttribute('type', 'hidden');
    
    $(myInputName).name = "nome_campi";
    $(myInputAlt).name = "alt_campi";
    $(myInputValue).name = "value_campi";
    var fChildren = myForm.getElements();
    //da modificareeee
    
    for (var i = 0; i < fChildren.length; i++) {
   
    
        //disattivo i campi hide
        if (Element.hasClassName($(fChildren[i]), 'hide')) {
            Form.Element.disable($(fChildren[i]));
        }
        
		 if (Element.hasClassName($(fChildren[i]), 'pureData')) {
            //questi sono dati di sianet
        }
		
        //preparo le tre variabili che contengono nomi valori e alt
        if ($(fChildren[i]).type != 'button' && $(fChildren[i]).type != 'reset' && $(fChildren[i]).type != 'submit' && $(fChildren[i]).name != 'legge_privacy' && !Element.hasClassName($(fChildren[i]), 'hide') && !Element.hasClassName($(fChildren[i]), 'pureData')) {
            try {

/*
 alert("name:"+!isNull($(fChildren[i]).name)+"\n"+
	"alt:"+!isNull($(fChildren[i]).getAttribute('alt'))+"\n"+
	"title:"+!isNull($(fChildren[i]).getAttribute('title'))+"\n"+
	"all:"+$(fChildren[i]).toString()+"\n");
 */
//Preparo gli Alt
                if (!isNull($(fChildren[i]).getAttribute('alt'))) {
                    $(myInputAlt).value =$(myInputAlt).value + $(fChildren[i]).getAttribute('alt') + separatore; 

                }else {
                    if (!isNull($(fChildren[i]).getAttribute('title'))) {
                        $(myInputAlt).value =$(myInputAlt).value + $(fChildren[i]).getAttribute('title') + separatore;

                    }
                    else {
						
						//controllo il caso per gli stati
						if(!isNull($(fChildren[i]).name)){
							 $(myInputAlt).value =$(myInputAlt).value + $(fChildren[i]).name + separatore; 
							
						}	
						
												   
					   }
				}
                //Preparo i name
                if (!isNull($(fChildren[i]).name)) {
                    $(myInputName).value =$(myInputName).value + $(fChildren[i]).getAttribute('name') + separatore;
                }
                
                //Preparo il value
				
                if (!isNull($(fChildren[i]).name)) {
				
					 if ($(fChildren[i]).getAttribute('id') == "nazione") {
							//trasformo i numeri delle nazioni in valori ATTENZIONE IL CAMPO SI DEVE CHIAMARE NAZIONE
							$(myInputValue).value = $(myInputValue).value + ARRAY_NAZIONI[$(fChildren[i]).value] + separatore;
						
						}else{
						$(myInputValue).value = $(myInputValue).value + pulisciStringa(separatore,$(fChildren[i]).value)+separatore;
						}
                    
                }
                
            } 
            catch (e) {
                alert("CorreggiForm:" + e.message);
            }
            
            
            
        }
    }
    
    //**************
    //alert($(myInputName).value+" \n "+$(myInputAlt).value+" \n "+$(myInputValue).value)
    // alert($(myInputAlt).value)
    // alert($(myInputValue).value)
    myForm.appendChild(myInputName);
    myForm.appendChild(myInputAlt);
    myForm.appendChild(myInputValue);
    
    
    return myForm;
}


function invia_ctrl(target){
    if (target == '') {
        target = 0;
    }
    var errorMsg = MSG.errorAlert;
	
	
	//HACKS VARI
	
	//Temporaneo per far funzionare i asmail di sianet
	if($('IDstato')){
	   $('IDstato').setAttribute('title','Nazione');
	   $('IDstato').setAttribute('id','nazione');
	}
	
	
	
	
	
	
	
    if (obbligatori(target) && !flgErrPag) {
    
        correggiForm(document.forms[target]).submit()
        //correggiForm(document.forms[target]);
    }
    else {
        for (var i = 0; i < elementiMancanti.length; i++) {
            errorMsg += MSG.theField + "'" + elementiMancanti[i] + "'" + MSG.isRequired + "\n";
        }
        alert(errorMsg);
    }
    
}

/*********************************************************/




//========================================================
//========== General scripts ============================
//========================================================





function setFieldsToUpperCase(thisObj, thisEvent){
    var key = thisEvent.keyCode;
    if ((key != 37) && (key != 39) && (key != 8) && (key != 46)) {
        var y = thisObj.value;
        thisObj.value = y.toUpperCase();
    }
}


function padLength(val, len){
    val = "" + val;
    while (val.length < len) {
        val = "0" + val;
    }
    return val;
}

function editKeyBoard(evt, objKeyb){
    /*	Function:		editKeyBoard
     Creation Date:	October 11, 2001
     Programmer:		Edmond Woychowsky
     Purpose:		The purpose of this function is to edit edit keyboard input
     to determine if the keystrokes are valid.
     
     Update Date:		Programmer:			Description:
     */
    try {
        
		var objForm = Event.element(evt);
		var keyCode = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
        if (window.event) {
            evt = window.event;
        }
       //log
	   // alert(objForm.name+evt.type+keyCode)
        
		strWork = objKeyb.getValid();
        strMsg = ''; // Error message
        blnValidChar = false; // Valid character flag
        
			
		// Part 1: Validate input
        if (!blnValidChar) {
			
            for (i = 0; i < strWork.length; i++) {
	
				if (keyCode == strWork.charCodeAt(i) || keyCode == 8) {
					blnValidChar = true;
	//				alert("Ok");
					return true;
				}
				
			}
        // Part 2: Build error message

            if (objKeyb.getMessage().toString().length != 0 ) {
				//alert('Error: ' + objKeyb.getMessage());
//						alert("KO"+window.event);
				// Clear invalid character
				if (window.event) {
					evt.returnValue = false;
				//e.cancelBubble = true;
				}
				if (evt.preventDefault) {
					//alert("KO-Firefox");
				 evt.preventDefault();
				//e.stopPropagation();
				}
				objForm.focus(); // Set focus
			 return false;	
			}
            
           
        }
        
    } 
    catch (e) {
        alert(e.message);
    }
    
}




function keybEdit(strValid, strMsg){
    /*	Function:		keybEdit
     Creation Date:	October 11, 2001
     Programmer:		Edmond Woychowsky
     Purpose:		The purpose of this function is to be a constructor for
     the keybEdit object.  keybEdit objects are used by the
     function editKeyBoard to determine which keystrokes are
     valid for form objects.  In addition, if an error occurs,
     they provide the error message.
     
     Please note that the strValid is converted to both
     upper and lower case by this constructor.  Also, that
     the error message is prefixed with 'Error:'.
     
     The properties for this object are the following:
     valid	=	Valid input characters
     message	=	Error message
     
     The methods for this object are the following:
     getValid()	=	Returns a string containing valid
     characters.
     getMessage()=	Returns a string containing the
     error message.
     Update Date:	Programmer:			Description:
     */
    //	Variables
    var reWork = new RegExp('[a-z]', 'gi'); //	Regular expression\
    //	Properties
    if (reWork.test(strValid)) 
        this.valid = strValid.toLowerCase() + strValid.toUpperCase();
    else 
        this.valid = strValid;
    
    if ((strMsg == null) || (typeof(strMsg) == 'undefined')) 
        this.message = '';
    else 
        this.message = strMsg;
    
    //	Methods
    this.getValid = keybEditGetValid;
    this.getMessage = keybEditGetMessage;
    
    function keybEditGetValid(){
        /*	Function:		keybEdit
         Creation Date:	October 11, 2001
         Programmer:		Edmond Woychowsky
         Purpose:		The purpose of this function act as the getValid method
         for the keybEdit object.  Please note that most of the
         following logic is for handling numeric keypad input.
         Update Date:		Programmer:			Description:
         */
        return this.valid.toString();
    }
    
    function keybEditGetMessage(){
        /*	Function:		keybEdit
         Creation Date:	October 11, 2001
         Programmer:		Edmond Woychowsky
         Purpose:		The purpose of this function act as the getMessage method
         for the keybEdit object.
         Update Date:	Programmer:			Description:
         */
        return this.message;
    }
}








function trim(StringToTrim){
    if (typeof(StringToTrim) != "string") {
        return StringToTrim;
    }
    var StringBlank = StringToTrim.substring(0, 1);
    while (StringBlank == " ") {
        StringToTrim = StringToTrim.substring(1, StringToTrim.length);
        StringBlank = StringToTrim.substring(0, 1);
    }
    StringBlank = StringToTrim.substring(StringToTrim.length - 1, StringToTrim.length);
    while (StringBlank == " ") {
        StringToTrim = StringToTrim.substring(0, StringToTrim.length - 1);
        StringBlank = StringToTrim.substring(StringToTrim.length - 1, StringToTrim.length);
    }
    return StringToTrim;
}



function impostaFuoco(id){
    document.$(id).focus();
    return;
}



function vemail(campo){

    if (flgErrPag && (cmpErr != campo)) {
        return;
    }
    var valore = $(campo).value;//eval(campo+'.value');
    if (valore == "") {
        flgErrPag = false;
        cmpErr = '';
        return '';
    }
    var_email = trim(valore);
    if (var_email.length != valore.length) {
        cmpErr = campo;
        flgErrPag = true;
        alert(MSG.spaceNotValidValue);
        $(campo).focus();
    }
    else {
        //verifico validit� indirizzo
        pos = var_email.indexOf("@");
        if (pos > 0) {
            if (var_email.substr(pos + 1).indexOf(".") < 0) {
                cmpErr = campo;
                flgErrPag = true;
                alert(MSG.emailNotValid);
                $(campo).focus();
            }
            else {
                flgErrPag = false;
                cmpErr = '';
            }
        }
        else {
            cmpErr = campo;
            flgErrPag = true;
            alert(MSG.emailNotValid);
            $(campo).focus();
        }
    }
}




function vint(campo){
    //esce subito se c'e' gia' un'errore in pagina
    if (flgErrPag && (cmpErr != campo)) 
        return;
    var valore = eval(campo + '.value');
    if (valore.search('[^0-9]') != -1 && valore != "") {
        cmpErr = campo;
        flgErrPag = true;
        eval(campo + ".select()");
        alert(MSG.notValidValue);
    }
    else {
        eval(campo + ".value='" + valore + "'");
        cmpErr = '';
        flgErrPag = false;
    }
}


function vintr(campo, range){
    //esce subito se c'� gi� un'errore in pagina
    if (flgErrPag && (cmpErr != campo)) 
        return;
    var valore = eval(campo + '.value');
    if (valore.search('[^0-9]') != -1 && valore != "") {
        cmpErr = campo;
        flgErrPag = true;
        eval(campo + ".select()");
        alert(MSG.notValidValue);
    }
    else {
        var lb = 0, ub = 0;
        lb = parseInt(range.substr(0, range.indexOf(":")));
        ub = parseInt(range.substr(range.indexOf(":") + 1));
        if ((parseInt(valore) < lb) || (parseInt(valore) > ub)) {
            cmpErr = campo;
            flgErrPag = true;
            eval(campo + ".select()");
            alert(MSG.notValidValue);
        }
        else {
            eval(campo + ".value='" + valore + "'");
            cmpErr = '';
            flgErrPag = false;
        }
    }
}


function verificaLunghezza(thisObj, eventObj, size){
    var oggetto = thisObj.value;
    var lunghezza = oggetto.length;
    var ch = eventObj.keyCode;
    
    if (lunghezza >= size) {
        ch = "";
        alert("Raggiunta lunghezza massima consentita di " + size + " caratteri.");
        return false;
    }
}

/*

\b indicates a backspace.

    \f indicates a form feed.

    \n indicates a new line.

    \r indicates a carriage return.

    \t indicates a tab.

    \\ indicates a backslash.

    \' indicates a single quote.

    \" indicates a double quote.










*/


var stdCom="\b\n\r\t";
var stdAccent=String.fromCharCode(232)+
String.fromCharCode(233)+
String.fromCharCode(249)+
String.fromCharCode(224)+
String.fromCharCode(242)+
String.fromCharCode(236);
var keybYN = new keybEdit('yn', MSG.notValidValue + 'Es.: \'Y\' or \'N\'.');
var keybNumeric = new keybEdit('01234567890., -°+/{}()][%'+stdCom, MSG.notValidValue + ':Numeric input only.');
var keybNumericOnly = new keybEdit('01234567890'+stdCom, MSG.notValidValue + ':Numeric input only.');
var keybAlpha = new keybEdit("abcdefghijklmnopqurstuvwxyzABCDEFGHILMNOPQRSTUVWZXYJK_-+.,;:@()/\\\"!%&* °'"+stdAccent+stdCom, MSG.notValidValue + ':Alpha input only.');
var keybAlphaOnly = new keybEdit("abcdefghijklmnopqurstuvwxyz "+stdAccent+stdCom, MSG.notValidValue + ':Alpha input only.');
var keybAlphaNumeric = new keybEdit("abcdefghijklmnopqurstuvwxyz01234567890_-+.,;:@()/\\\"!%?&* °'"+stdAccent+stdCom, MSG.notValidValue + ':Alpha-numeric input only.');
var keybAlphaNumericOnly = new keybEdit("abcdefghijklmnopqurstuvwxyz01234567890 "+stdCom, MSG.notValidValue + ':Alpha-numeric input only.');
var keybDecimal = new keybEdit('01234567890,.'+stdCom, MSG.notValidValue + ':Decimal input only.');
var keybDate = new keybEdit('01234567890/'+stdCom, MSG.notValidValue + ':Date input only');
